export const Validators = {
  required(val: string | number) {
    if (typeof val === 'number') return !!val
    return !!val && val.length > 0
  },
  minLength(minlength: number) {
    return (val: string) => {
      if (val == null || val === '') return true
      const maxLengthReg = new RegExp(`^.{${minlength},}$`)
      return maxLengthReg.test(val)
    }
  },
  maxLength(maxlength: number) {
    return (val: string) => {
      if (val == null || val === '') return true
      const maxLengthReg = new RegExp(`^.{0,${maxlength}}$`)
      return maxLengthReg.test(val)
    }
  },
  pattern(reg: RegExp) {
    return (val: string) => {
      if (val == null || val === '') return true
      return reg.test(val)
    }
  },
  min(minValue: number) {
    return (val: number) => {
      if (!val) return false
      return Math.min(val, minValue) === minValue
    }
  },
  max(maxValue: number) {
    return (val: number) => {
      if (!val) return false
      return Math.max(val, maxValue) === maxValue
    }
  },
}

import { FormControl } from '@angular/forms'
export const utilsValidatorsRequired = function(control: FormControl) {
  let value = control.value === 0 ? control.value : control.value || ''
  if (typeof value === 'string') {
    value = value.trim()
  }
  const isValid = value.length !== 0
  return isValid ? null : { required: true }
}
